﻿using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using star_questionnair.DTOs;
using star_questionnair.Models;
using star_questionnair.Services.impl;
using star_questionnair.Utilities;
using star_questionnairquestionnair.Services;

namespace star_questionnair.Controllers;

[ApiController]
[Route("user")]
public class UserController : ControllerBase
{
    private readonly IUserService _userService;
    
    private readonly EmailService _emailService;

    public UserController(IUserService userService,EmailService emailService)
    {
        _userService = userService;
        _emailService = emailService;
    }

    [HttpGet("/user/detailById/{id}")]
    public async Task<IActionResult> GetById(int id)
    {
        var user = await _userService.GetByIdAsync(id);
        if (user == null) return NotFound();
        return Ok(user);
    }
    
    [HttpGet("/user/detailByName/{name}")]
    public async Task<IActionResult> DetailByName(string name)
    {
        var user = await _userService.GetByUserNameAsync(name);
        if (user == null)
        {
            return NotFound(new { message = "用户未找到" });
        }
        return Ok(new { success = true, data = user });
    }


    [HttpPost("/user/addUser")]
    public async Task<IActionResult> AddUser([FromBody] User user)
    {
        // 调用服务层的方法，检查用户名是否已存在
        bool isUsernameExist = await _userService.IsUsernameExistAsync(user.UserName);
    
        if (isUsernameExist)
        {
            return BadRequest("重复用户名");
        }
        await _userService.AddUserAsync(user);
        
        return Ok(new { 
            success = true, 
            message = "注册成功", 
            data = user // 包含注册后的用户信息
        });
    }
    
    [HttpPost("/user/login")]
    public async Task<IActionResult> Login([FromQuery] string userName, [FromQuery] string password)
    {
        string message = await _userService.PasswordSignInAsync(userName, password);
        
        if (message == "登陆成功")
        {
            return Ok(new
            {
                success = true,
                message = "登录成功"
            });  // 200 OK with success message
        }
        else if (message == "未知账户" || message == "用户名或密码错误")
        {
            return Unauthorized(new { message });  // 401 Unauthorized with error message
        }
        
        return BadRequest(new { message = "登录失败" });
    }
    
    [HttpPost("/user/logout")]
    public async Task<IActionResult> Logout()//暂时没有实际逻辑
    {
        return Ok(new { success = true });
    }


    [HttpPut("editUserInfo")]
    public async Task<IActionResult> UpdateUser([FromBody] User user)
    {
        await _userService.UpdateUserAsync(user);
        return Ok(new { success = true });
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteUser(int id)
    {
        await _userService.DeleteUserAsync(id);
        return NoContent();
    }
    
    [HttpPost("forgot/{userId}")]
    public async Task<IActionResult> ForgotPassword(int userId)
    {
        // 查找用户
        var user = await _userService.GetByIdAsync(userId);
        if (user == null)
        {
            return NotFound(new { message = "未能找到用户" });
        }

        string email = user.Email;
        if (string.IsNullOrEmpty(email))
        {
            return BadRequest(new { message = "该用户未绑定邮箱" });
        }

        // 生成验证码
        string verificationCode = VerificationCodeGenerator.GenerateCode();
            
        // 保存验证码到用户表或缓存
        await _userService.SaveVerificationCodeAsync(userId, verificationCode);

        // 发送验证码邮件
        await _emailService.SendSimpleMessageAsync(user.UserName,email, "Password Reset Verification Code", $"Your verification code is: {verificationCode}");

        return Ok(new {success=true,data= verificationCode });
    }

    [HttpPost("/user/resetPassword")]
    public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordDTO request)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);  // 返回详细的错误信息
        }
        
        var result = await _userService.ResetPasswordAsync(request.UserId, request.NewPassword, request.Code);

        if (result == UserService.ResetPasswordResult.InvalidCode)
        {
            return BadRequest("验证码无效或已过期。");
        }

        if (result == UserService.ResetPasswordResult.UserNotFound)
        {
            return NotFound("用户未找到。");
        }

        return Ok(new { success = true, data = result });
    }


}